// @ts-nocheck
import {useEffect, useState} from 'react'
import {queryCommunityBySubDistrict, queryCommunityByName, getCommunityById} from '@/services/community'
import {Select} from 'antd'

let timeout
const CommunitySelect = (props) => {
  const {defaultValue, onChange, onSelect, district, subDistrict, back} = props
  const [value, setValue] = useState(null)
  const [data, setData] = useState([])
  const [loading,setLoading] = useState(false)
  useEffect(() => {
    /*判断默认值*/
    if (back) {
      setValue(defaultValue)
    } else {
      setValue(null)
    }
    console.log(subDistrict)
    queryCommunityBySubDistrict({subdistrict_id: subDistrict}).then(res => {
      setData(res.data)
    })

  }, [subDistrict])
  useEffect(() => {
    if (back) {
      setValue(defaultValue)
    } else {
      setValue(null)
    }
  }, [district])
  const handleSearch = (e) => {
    if (e) {
      setLoading(true)
      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }
      timeout = setTimeout(() => {
        queryCommunityByName({name: e}).then(res => {
          setData(res.data)
          setLoading(false)
        })
      }, 500)
    }
  }
  const handleSelect = (e) => {
    getCommunityById({community_id: e}).then(res => {
      if (onSelect) {
        onSelect(res.data)
      }
    })


  }
  return (
    <Select
      value={value}
      allowClear
      showSearch
      loading={loading}
      onSearch={(e) => handleSearch(e)}
      onChange={(e) => {
        setValue(e);
        onChange(e);
      }}
      onSelect={(e) => handleSelect(e)}
      placeholder={'请选择所属园区'}
    >
      {data.map(v => <Select.Option key={v.community_id} value={v.community_id}>{v.name}</Select.Option>)}
    </Select>
  );
};

export default CommunitySelect;
